package com.ape.mapsa.produccion.dao;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.ape.mapsa.produccion.model.OrdenProduccion;

@Repository
public class OpDAOImpl extends GenericDAOImpl<OrdenProduccion, Long> implements OpDAO {

	private static final Logger log = Logger.getLogger(OpDAOImpl.class);

	@SuppressWarnings("unchecked")
	@Override
	@Transactional(readOnly = true)
	public List<OrdenProduccion> getAllByState(Long l) {
		log.info("Getting orden prod by state " + l);
		List<OrdenProduccion> ordens = null;
		if (l != null) {
			Session currentSession = sessionFactory.getCurrentSession();
			Criteria criteria = currentSession.createCriteria(OrdenProduccion.class);
			criteria.setFetchMode("opComments", FetchMode.JOIN);
			criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
			criteria = criteria.createCriteria("estadoProduccion").add(Restrictions.eq("id", l));
			ordens = criteria.list();
		} else {
			Session currentSession = sessionFactory.getCurrentSession();
			Criteria criteria = currentSession.createCriteria(OrdenProduccion.class);
			criteria.setFetchMode("opComments", FetchMode.JOIN);
			criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
			ordens = criteria.list();
		}
		return ordens;
	}

	@Override
	@Transactional(readOnly = true)
	public Integer countOrdenProdByState(Long l) {
		log.debug("Getting orden prod by state " + l);
		Query createQuery = sessionFactory.getCurrentSession().createQuery("select count(*) from OrdenProduccion where estadoProduccion = " + l);
		int intValue = ((Long) createQuery.iterate().next()).intValue();
		return intValue;
	}

}
